﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TSOL.FastSPWeb.ValueObjects;

namespace TSOL.FastSPWeb.Core
{
    class FastSPItemsGarbageCollectorThread
    {
        static Thread GarbageCollectorThread;

        public static void Start() {
            (GarbageCollectorThread = new Thread(FastSPItemsGarbageCollectorTask)).Start();
        }
        public static void Stop()
        {
            GarbageCollectorThread.Abort();
        }
        static void FastSPItemsGarbageCollectorTask()
        {
            while ((Thread.CurrentThread.ThreadState != ThreadState.AbortRequested) && (Thread.CurrentThread.ThreadState != ThreadState.StopRequested) && (Thread.CurrentThread.ThreadState != ThreadState.SuspendRequested))
            {
                Thread.Sleep(3 * 60 * 1000); // 3 min. 
                lock (FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.ItemsCacheDictionary)
                {
                    DateTime invalidateTime = DateTime.Now.Subtract(FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.DefaultItemsCachedTimeSpan);
                    foreach (SPItemsCacheCollection _SPCacheCollection in FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.ItemsCacheDictionary.Values)
                    {
                        var ÍnvalidatedItems = _SPCacheCollection.Where(a => a.LastUsed <= invalidateTime).Select(n => n);
                        if (ÍnvalidatedItems.Any())
                        {
                            List<SPItemsCacheEntity> removedKeys = new List<SPItemsCacheEntity>();
                            foreach (SPItemsCacheEntity _cache in ÍnvalidatedItems)
                            {
                               removedKeys.Add(_cache);
                            }
                            foreach (SPItemsCacheEntity key in removedKeys)
                                _SPCacheCollection.Remove(key);
                        }
                    }
                }
            }
        }

    }
}
